package com.jiyu.zhang.jersey.JerseyServerDemo;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.StreamingOutput;

/**
 * Root resource (exposed at "myresource" path)
 */
@Path("myresource")
public class MyResource {

    /**
	 * Method handling HTTP GET requests. The returned object will be sent to
	 * the client as "text/plain" media type.
	 *
	 * @return String that will be returned as a text/plain response.
	 */
	@GET
	@Path("got")
	@Produces(MediaType.TEXT_PLAIN)
	public String getIt() {
		return "Got it!";
	}

	@GET
	@Path("download")
	@Produces(MediaType.APPLICATION_OCTET_STREAM)
	public Response down(){
		final List<InputStream> list = new ArrayList<InputStream>();
		FileInputStream input = null;
		try {
			input = new FileInputStream(new File("D:/UM_4.0.110130.exe"));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		list.add(input);
		StreamingOutput stream = new StreamingOutput() {
			@Override
			public void write(OutputStream output) throws IOException, WebApplicationException {

				ZipOutputStream zipOut = new ZipOutputStream(output);
				byte[] data = new byte[1024];
    			int i = 0;
				for (InputStream in : list) {
					i++;
					zipOut.putNextEntry(new ZipEntry("um" + i + ".exe"));
					// 目的在于防止最后一次读取的字节小于buffer长度， 否则会自动被填充0
					int temp = 0;
					while ((temp = in.read(data)) != -1) {
						zipOut.write(data, 0, temp);
					}
					zipOut.closeEntry();
				}
				// ou.flush();
				// // 关闭输出流，防止文件解压时出现“不可预料的压缩文件末端”错误
				// ou.close();
				// 完成写入zip输出流的内容，无需关闭底层流
				zipOut.finish();
			}
		};

		return Response.ok(stream, MediaType.APPLICATION_OCTET_STREAM).header("content-disposition",
				"attachment; filename = myfile.zip").build();

	}

}